import React, {Component} from 'react'
import {
    DeviceEventEmitter,
    Linking,
    ListView,
    RefreshControl,
    ScrollView,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import I18n from "../../../res/language/i18n";
import ViewUtils from "../../../utils/ViewUtils";
import MatrixBusinessInfoPage from "./MatrixBusinessInfoPage";
import CommonUtils from "../../../common/CommonUtils";
import AlertDialog from "../../../custom/AlertDialog";
import MatrixSubBCPage from "./MatrixSubBCPage";
import SlideMenu from "../../../menu/SlideMenu";


const ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2,
});
export default class SubAccountsPage extends Component {


    constructor(props) {
        super(props);

        let isNewAssociates = props.type === 'newAssociates';
        this.menuData = [
            isNewAssociates ? {name: I18n.t('default.userName'), code: 7} : null,
            isNewAssociates ? {name: I18n.t('default.phone'), code: 8} : null,
            {name: I18n.t('b.businessCenter'), code: 0},
            {name: I18n.t('default.identity'), code: 1},
            {name: I18n.t('b.regsitrationPack'), code: 2},
            {name: I18n.t('b.bsuinessSet'), code: 3},
            {name: I18n.t('default.volume'), code: 4},
            {name: I18n.t('default.myActivity'), code: 5},
            {name: I18n.t('b.activationDate'), code: 6}
        ];

        this.state = {
            usersData: this.props.users ? this.props.users : [],
            alertVisible: false,
            selectData: null,
        }
    }


    componentDidMount() {
        if (!this.props.users) {
            this.onLoadData()
        }
    }


    /**
     * 获取摸个用户的子账号
     */
    onLoadData() {
        CommonUtils.showLoading();


        let rank = this.props.rank ? '&rank=' + this.props.rank : '';

        new IparNetwork().getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'main_user_id=' + this.props.userId + rank)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    this.setState({
                        usersData: result.data || [],
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));

                }

            })
            .catch((error) => {
                CommonUtils.dismissLoading();


                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('MatrixPlanPage-----onLoadData--error: ', error);
            })
    }

    renderMenuViews(rowData, index) {
        if (rowData.user_id === rowData.main_user_id) return null;


        return <TouchableOpacity
            onPress={() => {
                let _mobile = rowData.mobile;
                _mobile = rowData.user_main ? rowData.user_main._mobile : _mobile;

                if (this.props.type !== 'newAssociates') {
                    let isCheckDetails = this.props.type === 'checkDetails';

                    let plansData = this.props.plansData;

                    let _planName = '';
                    let _planIndex = -1;
                    if (plansData) {
                        for (let i = 0, len = plansData.length; i < len; i++) {
                            let plansDatum = plansData[i];
                            if (plansDatum.rank === rowData.rank) {
                                _planName = plansDatum.name;
                                _planIndex = i;
                                break;
                            }
                        }
                    }


                    let _component = null;
                    let _params = {};
                    if (rowData.rank > 1 && rowData.rank < 5) {
                        if (isCheckDetails) {
                            this.props.navigator.pop();
                            this.props.callBack && this.props.callBack(_planIndex + 1);
                            return;
                        } else {
                            _component = MatrixBusinessInfoPage;
                        }
                    } else if (rowData.rank > 4) {
                        _component = isCheckDetails ? MatrixSubBCPage : MatrixBusinessInfoPage;

                        if (isCheckDetails) {
                            _params = {
                                usersData: [rowData],
                                selectDataIndex: 0,
                            }
                        } else {
                        }
                    }

                    if (_component) {

                        this.props.navigator.push({
                            component: _component,
                            name: _component + '',
                            params: {
                                ..._params,
                                titleText: _planName,
                                title: _planName,
                                userData: rowData,
                                index: index,
                            },
                        })
                    }
                } else {
                    _mobile && Linking.openURL(`tel:${_mobile}`);
                }
            }}
            onLongPress={() => {
                if (this.props.type !== 'newAssociates') {
                    this.setState({
                        alertVisible: true,
                        selectData: rowData,
                    })
                }
            }}
            style={[StyleUtils.justifySpace]}>

            {this.menuData.map((item, i) => {
                if (!item) return null;

                let text = 0;

                let _levelName = rowData.user_level ? rowData.user_level.level_name : '';
                let _userName = rowData.nick_name ? rowData.nick_name : rowData.first_name;


                let userMain = rowData.user_main;
                if (userMain) {
                    _levelName = !_levelName && userMain.user_level ? userMain.user_level.level_name : _levelName;
                    _userName = userMain.nick_name ? userMain.nick_name : userMain.first_name
                }


                switch (item.code) {
                    case 0:
                        text = rowData.rand_id;
                        break;
                    case 1:
                        text = _levelName;
                        break;
                    case 2:
                        text = rowData.is_reg_pack === 0 ? I18n.t('default.notActivated') : I18n.t('default.activated');
                        break;
                    case 3:
                        text = rowData.is_buy === 0 ? I18n.t('default.notActivated') : I18n.t('default.activated');
                        break;
                    case 4://left_balance
                        text = rowData.is_prereg === 0 ? I18n.t('default.notActivated') : I18n.t('default.activated');
                        break;
                    case 5://right_balance
                        text = rowData.is_active === 0 ? I18n.t('default.notActivated') : I18n.t('default.activated');
                        break;
                    case 6:
                        text = rowData.active_time && rowData.active_time.substring(0, 11);
                        break;
                    case 7:
                        text = _userName;
                        break;
                    case 8:
                        text = rowData.user_main ? rowData.user_main.mobile : rowData.mobile;
                        break;
                }


                return <View style={[StyleUtils.center, {
                    width: 88,
                    height: 42,
                    backgroundColor: 'black'
                }, {
                    height: 32,
                    backgroundColor: index % 2 === 0 ? "white" : '#f0f0f0'
                }]}>
                    <Text
                        numberOfLines={2}
                        style={[{
                            color: 'black',
                            fontSize: 10,
                            textAlign: 'center',
                            paddingLeft: 4,
                            paddingRight: 4
                        }, StyleUtils.smallFont]}>{text}</Text>
                </View>

            })}

        </TouchableOpacity>
    }


    render() {
        return (<View style={StyleUtils.flex}>
            <Navigation
                onClickLeftBtn={() => this.props.navigator.pop()}/>
            <View style={{padding: 16}}>
                {ViewUtils.getTitleView(this.props.title ? this.props.title : I18n.t('b.ActivatedBusiness'),)}
            </View>
            <ScrollView
                horizontal={true}>
                <View>
                    <View style={StyleUtils.justifySpace}>

                        {this.menuData.map((item, i) => {
                            if (!item) return null
                            return <View style={[StyleUtils.center, {
                                width: 88,
                                height: 42,
                                backgroundColor: 'black'
                            }]}>
                                <Text
                                    numberOfLines={2}
                                    style={[{
                                        color: 'white',
                                        fontSize: 10,
                                        textAlign: 'center',
                                        paddingLeft: 4,
                                        paddingRight: 4
                                    }, StyleUtils.smallFont]}>{item.name}</Text>
                            </View>

                        })}

                    </View>


                    <ListView
                        renderRow={(rowData, sectionID, rowID) => this.renderMenuViews(rowData, rowID)}
                        dataSource={ds.cloneWithRows(this.state.usersData)}
                    />


                </View>

            </ScrollView>
            {this.state.usersData.length <= 0 &&
            <Text style={[StyleUtils.smallFont, {
                flex: 1,
                textAlign: 'center'
            }]}>{I18n.t('default.noData')}</Text>}
            <View style={{padding: 16}}>
                {ViewUtils.getButton(I18n.t('b.back'), () => this.props.navigator.pop(), {
                    marginBottom: 46,
                    height: 42
                })}
            </View>


            <AlertDialog
                contentTv={I18n.t('b.defaultBusiness')}
                leftBtnOnclick={() => {
                    let userData = this.state.selectData;
                    CommonUtils.saveUserInfo(userData,);
                    const {navigator} = this.props;
                    navigator.resetTo({
                        component: SlideMenu,
                        name: 'SlideMenu',
                        params: {
                            ...this.props,
                        }
                    });
                }}
                visible={this.state.alertVisible}
                requestClose={() => this.setState({alertVisible: false})}/>


        </View>)
    }

}